<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li><a href="#/home">首页</a></li>
        <li><a href="#/about">关于</a></li>
    </ul>
    <!-- 当 url 变更后，展示对应的代码片段 -->
    <div id="root"></div>

    <script>
        const routes =[
            {
                path:'/home',
                component:()=>{
                    return `<h1>首页</h1>`
                },

            },
            {
                path:'/about',
                component:()=>{
                    return `<h1>关于</h1>`
                }
            }
        ]

        // 1. 怎么知道 url 变更了
        // 2. 浏览器不能刷新 hash
        window.addEventListener('hashchange',(e)=>{
            console.log('url 变更了')
            console.log(location.hash);
            renderView(location.hash);
        })
        // 3. 怎么根据 url 展示对应的组件
        function renderView(url){
            const index = routes.findIndex(item=>{
                return ('#'+item.path) === url
            });
            let routerView =document.getElementById('root')
            routerView.innerHTML=routes[index].component();
        }

        window.addEventListener('DOMContentLoaded',(e)=>{
            renderView(location.hash);
        })
    </script>
</body>
</html>